/* ========== 工具 ========== */
const $ = q => document.querySelector(q);
const random = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min;

/* 数字滚动 */
function animateCounter(el) {
    const target = +el.dataset.target;
    const duration = 1000;
    const step = target / (duration / 16);
    let now = 0;
    const tick = () => {
        now += step;
        if (now >= target) {
            el.textContent = target.toLocaleString();
            return;
        }
        el.textContent = Math.floor(now).toLocaleString();
        requestAnimationFrame(tick);
    };
    tick();
}

/* 全屏 */
const fullscreenBtn = document.querySelector('#fullscreenBtn');
if (fullscreenBtn) {
    fullscreenBtn.addEventListener('click', () => {
        if (document.fullscreenElement) {
            document.exitFullscreen();
        } else {
            document.documentElement.requestFullscreen().catch(err => {
                console.error('全屏请求失败:', err);
            });
        }
    });
}

/* 初始化所有计数器 */
document.querySelectorAll('.counter').forEach(animateCounter);

/* ========== 热点词云 ========== */
const hotspotData = {
    '1h': [
        { text: '元旦假期', value: 100 },
        { text: '2025年新年计划', value: 88 },
        { text: '春节出行', value: 82 },
        { text: '人工智能大模型', value: 75 },
        { text: '冬奥会', value: 70 },
        { text: '新能源车销量', value: 65 },
        { text: 'ChatGPT', value: 60 },
        { text: '元宇宙', value: 55 },
        { text: '健康饮食', value: 50 },
        { text: '远程办公', value: 48 },
        { text: '数字人民币', value: 45 },
        { text: '环保生活', value: 42 },
        { text: '虚拟现实', value: 38 },
        { text: '直播电商', value: 35 },
        { text: '数字藏品', value: 32 }
    ],
    '6h': [
        { text: '元旦假期', value: 100 },
        { text: '2025年新年计划', value: 88 },
        { text: '春节出行', value: 82 },
        { text: '人工智能大模型', value: 75 },
        { text: '冬奥会', value: 70 },
        { text: '新能源车销量', value: 65 },
        { text: 'ChatGPT', value: 60 },
        { text: '元宇宙', value: 55 },
        { text: '健康饮食', value: 50 },
        { text: '远程办公', value: 48 },
        { text: '数字人民币', value: 45 },
        { text: '环保生活', value: 42 },
        { text: '虚拟现实', value: 38 },
        { text: '直播电商', value: 35 },
        { text: '数字藏品', value: 32 },
        { text: '元学习', value: 30 },
        { text: '量子计算', value: 28 },
        { text: '低碳生活', value: 26 },
        { text: '数字孪生', value: 24 },
        { text: '可持续发展', value: 22 }
    ],
    '24h': [
        { text: '元旦假期', value: 100 },
        { text: '2025年新年计划', value: 88 },
        { text: '春节出行', value: 82 },
        { text: '人工智能大模型', value: 75 },
        { text: '冬奥会', value: 70 },
        { text: '新能源车销量', value: 65 },
        { text: 'ChatGPT', value: 60 },
        { text: '元宇宙', value: 55 },
        { text: '健康饮食', value: 50 },
        { text: '远程办公', value: 48 },
        { text: '数字人民币', value: 45 },
        { text: '环保生活', value: 42 },
        { text: '虚拟现实', value: 38 },
        { text: '直播电商', value: 35 },
        { text: '数字藏品', value: 32 },
        { text: '元学习', value: 30 },
        { text: '量子计算', value: 28 },
        { text: '低碳生活', value: 26 },
        { text: '数字孪生', value: 24 },
        { text: '可持续发展', value: 22 },
        { text: '智慧城市', value: 20 },
        { text: '区块链', value: 18 },
        { text: '边缘计算', value: 16 },
        { text: '生物科技', value: 14 }
    ]
};

// 添加全局样式
function addGlobalStyles() {
    const style = document.createElement('style');
    style.textContent = `
        @keyframes floatAnimation {
            0% { transform: translate(0, 0) rotate(0deg) translateY(0); }
            25% { transform: translate(10px, -10px) rotate(2deg) translateY(-5px); }
            50% { transform: translate(0, 0) rotate(0deg) translateY(0); }
            75% { transform: translate(-10px, 10px) rotate(-2deg) translateY(5px); }
            100% { transform: translate(0, 0) rotate(0deg) translateY(0); }
        }
        
        @keyframes pulseAnimation {
            0% { transform: scale(1); box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1); }
            50% { transform: scale(1.05); box-shadow: 0 10px 20px rgba(0, 0, 0, 0.2); }
            100% { transform: scale(1); box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1); }
        }
        
        @keyframes fadeInUp {
            from {
                opacity: 0;
                transform: translateY(20px) scale(0.9);
            }
            to {
                opacity: 1;
                transform: translateY(0) scale(1);
            }
        }
        
        .word-cloud-item {
            animation: fadeInUp 0.5s ease forwards, floatAnimation 6s ease-in-out infinite;
            cursor: pointer;
            user-select: none;
            font-weight: 500;
            will-change: transform, box-shadow;
            transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
            position: relative;
            display: inline-block;
            text-align: center;
            word-break: keep-all;
            white-space: nowrap;
            backface-visibility: hidden;
            perspective: 1000px;
        }
        
        .word-cloud-item:hover {
            animation-play-state: paused;
            transform: scale(1.4) translateY(-10px) !important;
            z-index: 100;
        }
        
        .word-cloud-item::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: inherit;
            border-radius: inherit;
            filter: blur(10px);
            opacity: 0.5;
            z-index: -1;
            transform: scale(1.1);
            transition: opacity 0.3s ease;
        }
        
        .word-cloud-item:hover::before {
            opacity: 0.8;
            transform: scale(1.2);
        }
        
        .particle {
            position: absolute;
            background: rgba(255, 255, 255, 0.3);
            border-radius: 50%;
            pointer-events: none;
            animation: floatAnimation 4s ease-in-out infinite;
            z-index: 0;
        }
        
        .hotspot-container {
            position: relative !important;
            min-height: 300px !important;
            overflow: hidden !important;
            background: radial-gradient(circle at center, rgba(102, 126, 234, 0.05), rgba(118, 75, 162, 0.05)) !important;
            border-radius: 16px !important;
        }
        
        .hotspot-container::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: linear-gradient(135deg, rgba(102, 126, 234, 0.05), rgba(118, 75, 162, 0.1));
            opacity: 0.5;
            z-index: 0;
        }
    `;
    document.head.appendChild(style);
}

// 创建粒子背景
function createParticleBackground(container) {
    // 清除旧的粒子
    const oldParticles = container.querySelectorAll('.particle');
    oldParticles.forEach(p => p.remove());
    
    const particleCount = 50;
    for (let i = 0; i < particleCount; i++) {
        const particle = document.createElement('div');
        particle.className = 'particle';
        
        // 随机大小
        const size = Math.random() * 5 + 1;
        particle.style.width = `${size}px`;
        particle.style.height = `${size}px`;
        
        // 随机位置
        particle.style.left = `${Math.random() * 100}%`;
        particle.style.top = `${Math.random() * 100}%`;
        
        // 随机透明度和动画延迟
        particle.style.opacity = Math.random() * 0.5 + 0.1;
        particle.style.animationDelay = `${Math.random() * 5}s`;
        particle.style.animationDuration = `${Math.random() * 10 + 5}s`;
        
        container.appendChild(particle);
    }
}

// 根据热度获取颜色
function getColorByValue(value) {
    // 热度从0-100映射到不同的颜色
    const colors = [
        { min: 0, max: 20, color: '#4caf50' },    // 绿色
        { min: 21, max: 40, color: '#2196f3' },   // 蓝色
        { min: 41, max: 60, color: '#ff9800' },   // 橙色
        { min: 61, max: 80, color: '#ff5722' },   // 深橙色
        { min: 81, max: 100, color: '#e91e63' }   // 粉红色
    ];
    
    const colorRange = colors.find(range => value >= range.min && value <= range.max);
    return colorRange ? colorRange.color : '#9e9e9e';
}

// 3D热点词云渲染 - 全新实现
function renderWordCloud(data) {
    // 确保添加全局样式
    if (!document.querySelector('style[data-cloud-styles]')) {
        const style = document.createElement('style');
        style.setAttribute('data-cloud-styles', 'true');
        addGlobalStyles();
    }
    
    // 获取两个容器（hotspotWords和hotspotTags）
    const containers = [
        $('#hotspotWords'),
        $('#hotspotTags')
    ].filter(Boolean);
    
    containers.forEach(container => {
        container.innerHTML = '';
        
        // 确保容器有正确的样式
        container.style.position = 'relative';
        container.style.width = '100%';
        container.style.height = '100%';
        container.style.minHeight = '300px';
        container.style.overflow = 'hidden';
        container.style.padding = '30px';
        container.style.display = 'flex';
        container.style.flexWrap = 'wrap';
        container.style.alignContent = 'center';
        container.style.justifyContent = 'center';
        container.style.gap = '15px';
        container.style.zIndex = '1';
        
        // 创建粒子背景
        createParticleBackground(container);
        
        // 为每个热点词创建元素
        data.forEach((word, index) => {
            const size = 12 + (word.value / 100) * 24; // 字体大小范围：12px - 36px
            const color = getColorByValue(word.value);
            const randomRotate = (Math.random() - 0.5) * 10; // -5°到5°的随机旋转
            const randomDelay = index * 0.05; // 错开动画时间
            
            const wordElement = document.createElement('div');
            wordElement.className = 'word-cloud-item';
            wordElement.textContent = word.text;
            
            // 基本样式
            wordElement.style.fontSize = `${size}px`;
            wordElement.style.color = color;
            wordElement.style.backgroundColor = `${color}20`; // 20%透明度的背景
            wordElement.style.border = `2px solid ${color}40`; // 40%透明度的边框
            wordElement.style.borderRadius = '25px';
            wordElement.style.padding = `${size * 0.25}px ${size * 0.5}px`;
            wordElement.style.margin = '5px';
            wordElement.style.textShadow = `0 2px 4px rgba(0, 0, 0, 0.2)`;
            wordElement.style.animationDelay = `${randomDelay}s`;
            wordElement.style.transform = `rotate(${randomRotate}deg)`;
            wordElement.style.zIndex = '10';
            
            // 设置不同的浮动动画持续时间
            const animationDuration = 5 + (Math.random() * 3);
            wordElement.style.animationDuration = `${animationDuration}s`;
            
            // 添加悬停效果
            wordElement.addEventListener('mouseenter', function() {
                this.style.transform = `scale(1.4) translateY(-10px) rotate(${randomRotate}deg)`;
                this.style.boxShadow = `0 15px 30px ${color}40`;
                this.style.color = color;
                this.style.backgroundColor = `${color}30`;
                this.style.borderColor = color;
            });
            
            wordElement.addEventListener('mouseleave', function() {
                this.style.transform = `rotate(${randomRotate}deg)`;
                this.style.boxShadow = 'none';
                this.style.color = color;
                this.style.backgroundColor = `${color}20`;
                this.style.borderColor = `${color}40`;
            });
            
            // 添加点击效果
            wordElement.addEventListener('click', function() {
                this.style.animation = 'pulseAnimation 0.6s ease-in-out';
                setTimeout(() => {
                    this.style.animation = '';
                }, 600);
                // 可以在这里添加点击后的更多交互
                console.log('热点词点击:', word.text, '热度:', word.value);
            });
            
            // 添加到容器
            container.appendChild(wordElement);
        });
    });
}

/* 刷新热点词云 */
function refreshHotspot() {
    const timeRange = $('#timeRangeSelect').value;
    const data = hotspotData[timeRange];
    
    // 添加洗牌效果
    const shuffledData = [...data].sort(() => 0.5 - Math.random());
    
    renderWordCloud(shuffledData);
    
    // 更新当前爆点
    const hottest = shuffledData[0].text;
    updateCurrentHotspot(hottest);
}

/* 更新当前爆点 */
function updateCurrentHotspot(hotspot) {
    const element = document.querySelector('#currentHotspot');
    if (!element) return;
    element.style.opacity = '0.5';
    setTimeout(() => {
        element.textContent = hotspot;
        element.style.opacity = '1';
    }, 300);
}

/* 时间范围切换 */
const timeRangeSelect = document.querySelector('#timeRangeSelect');
if (timeRangeSelect) {
    timeRangeSelect.addEventListener('change', refreshHotspot);
}

/* ========== 热点趋势图 ========== */
let hotspotTrendChart;
const hotspotTrendChartEl = document.querySelector('#hotspotTrendChart');
if (hotspotTrendChartEl) {
    hotspotTrendChart = echarts.init(hotspotTrendChartEl);
}
const timeLabels = ['00:00', '03:00', '06:00', '09:00', '12:00', '15:00', '18:00', '21:00'];
const trendData1 = [120, 200, 150, 80, 70, 110, 130, 180]; // 节日假期相关
const trendData2 = [82, 93, 90, 94, 70, 96, 84, 82]; // 人工智能相关
const trendData3 = [30, 40, 35, 20, 80, 60, 70, 50]; // 新能源相关

function initHotspotTrendChart() {
    if (!hotspotTrendChart) return;
    hotspotTrendChart.setOption({
        backgroundColor: 'transparent',
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                type: 'cross',
                label: {
                    backgroundColor: '#6a7985'
                }
            }
        },
        legend: {
            data: ['节日假期', '人工智能', '新能源'],
            textStyle: {
                color: '#8892b0'
            },
            top: 0
        },
        grid: {
            left: 40, right: 20, top: 40, bottom: 40
        },
        xAxis: {
            type: 'category',
            boundaryGap: false,
            data: timeLabels,
            axisLine: { lineStyle: { color: '#334455' } },
            axisLabel: { color: '#8892b0' }
        },
        yAxis: {
            type: 'value',
            axisLine: { lineStyle: { color: '#334455' } },
            axisLabel: { color: '#8892b0' },
            splitLine: {
                lineStyle: {
                    color: 'rgba(255, 255, 255, 0.05)'
                }
            }
        },
        series: [
            {
                name: '节日假期',
                type: 'line',
                smooth: true,
                stack: 'Total',
                lineStyle: { width: 3, color: '#00d4ff' },
                areaStyle: {
                    color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                        { offset: 0, color: 'rgba(0, 212, 255, 0.5)' },
                        { offset: 1, color: 'rgba(0, 212, 255, 0.1)' }
                    ])
                },
                emphasis: {
                    focus: 'series'
                },
                data: trendData1
            },
            {
                name: '人工智能',
                type: 'line',
                smooth: true,
                stack: 'Total',
                lineStyle: { width: 3, color: '#ff0050' },
                areaStyle: {
                    color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                        { offset: 0, color: 'rgba(255, 0, 80, 0.5)' },
                        { offset: 1, color: 'rgba(255, 0, 80, 0.1)' }
                    ])
                },
                emphasis: {
                    focus: 'series'
                },
                data: trendData2
            },
            {
                name: '新能源',
                type: 'line',
                smooth: true,
                stack: 'Total',
                lineStyle: { width: 3, color: '#ffd740' },
                areaStyle: {
                    color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                        { offset: 0, color: 'rgba(255, 215, 64, 0.5)' },
                        { offset: 1, color: 'rgba(255, 215, 64, 0.1)' }
                    ])
                },
                emphasis: {
                    focus: 'series'
                },
                data: trendData3
            }
        ]
    });
}

/* ========== 热点分类分布 ========== */
let categoryChart;
const categoryChartEl = document.querySelector('#hotspotCategoryChart');
if (categoryChartEl) {
    categoryChart = echarts.init(categoryChartEl);
}
const categoryData = [
    { value: 35, name: '节日假期', itemStyle: { color: '#00d4ff' } },
    { value: 25, name: '人工智能', itemStyle: { color: '#ff0050' } },
    { value: 15, name: '新能源', itemStyle: { color: '#ffd740' } },
    { value: 12, name: '健康生活', itemStyle: { color: '#4caf50' } },
    { value: 8, name: '数字金融', itemStyle: { color: '#9c27b0' } },
    { value: 5, name: '其他', itemStyle: { color: '#ff9800' } }
];

function initCategoryChart() {
    if (!categoryChart) return;
    
    // 为分类数据添加渐变色配置和额外属性
    const categoryDataWithGradient = categoryData.map(item => ({
        ...item,
        itemStyle: {
            color: new echarts.graphic.RadialGradient(0.4, 0.3, 1, [
                { offset: 0, color: item.itemStyle.color },
                { offset: 1, color: adjustColorBrightness(item.itemStyle.color, -30) }
            ]),
            borderRadius: 10,
            borderColor: 'rgba(10, 14, 39, 0.8)',
            borderWidth: 2
        },
        emphasis: {
            itemStyle: {
                color: new echarts.graphic.RadialGradient(0.4, 0.3, 1, [
                    { offset: 0, color: adjustColorBrightness(item.itemStyle.color, 30) },
                    { offset: 1, color: item.itemStyle.color }
                ]),
                shadowBlur: 25,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.8)'
            },
            scaleSize: 15 // 选中时放大
        },
        select: {
            itemStyle: {
                color: new echarts.graphic.RadialGradient(0.4, 0.3, 1, [
                    { offset: 0, color: adjustColorBrightness(item.itemStyle.color, 20) },
                    { offset: 1, color: item.itemStyle.color }
                ]),
                borderColor: '#fff',
                borderWidth: 3
            },
            scaleSize: 10
        }
    }));
    
    // 计算总数用于中心显示
    const totalCount = categoryData.reduce((sum, item) => sum + item.value, 0);
    
    // 获取热点类型的图标
    const getCategoryIcon = (name) => {
        const iconMap = {
            '节日假期': '🎊',
            '人工智能': '🤖',
            '新能源': '⚡',
            '健康生活': '💚',
            '数字金融': '💰',
            '其他': '📌'
        };
        return iconMap[name] || '📊';
    };
    
    categoryChart.setOption({
        backgroundColor: 'transparent',
        tooltip: {
            trigger: 'item',
            formatter: function(params) {
                // 避免显示内圈装饰的数据
                if (params.seriesName === '内圈装饰') return '';
                
                return `
                    <div style="padding: 10px; border-radius: 8px; background: rgba(10, 14, 39, 0.9); border: 1px solid #4299e1;">
                        <div style="font-weight: bold; margin-bottom: 5px; color: ${params.color};">
                            ${getCategoryIcon(params.name)} ${params.name}
                        </div>
                        <div>数量: <span style="color: #4299e1; font-weight: bold;">${params.value}</span></div>
                        <div>占比: <span style="color: #4299e1; font-weight: bold;">${params.percent}%</span></div>
                        <div>总数: <span style="color: #8892b0;">${totalCount}</span></div>
                    </div>
                `;
            },
            backgroundColor: 'rgba(10, 14, 39, 0.9)',
            borderColor: '#4299e1',
            borderWidth: 1,
            textStyle: {
                color: '#fff'
            },
            // 添加动画效果
            enterable: true,
            transitionDuration: 0.3
        },
        legend: {
            orient: 'vertical',
            left: 'left',
            top: 'middle',
            textStyle: {
                color: '#8892b0',
                fontSize: 14,
                padding: [0, 0, 5, 0],
                // 添加文字阴影效果
                textShadowBlur: 5,
                textShadowColor: 'rgba(0, 0, 0, 0.5)'
            },
            formatter: function(name) {
                const item = categoryData.find(d => d.name === name);
                return `${getCategoryIcon(name)} ${name} (${item.value})`;
            },
            itemWidth: 15,
            itemHeight: 15,
            itemGap: 15,
            // 图例项的鼠标悬停效果
            emphasis: {
                textStyle: {
                    color: '#fff',
                    fontSize: 15
                }
            }
        },
        series: [
            {
                name: '热点分类',
                type: 'pie',
                radius: ['40%', '70%'],
                center: ['65%', '50%'],
                avoidLabelOverlap: false,
                startAngle: 90,
                clockWise: true,
                data: categoryDataWithGradient,
                // 启用点击交互
                selectedMode: 'single',
                selectedOffset: 20,
                // 添加动画效果
                animationType: 'scale',
                animationEasing: 'elasticOut',
                animationDelay: function(idx) {
                    return Math.random() * 200;
                },
                animationDuration: 1000,
                // 添加外部标签
                label: {
                    show: true,
                    position: 'outside',
                    formatter: function(params) {
                        return `${params.name}\n${params.percent}%`;
                    },
                    color: '#fff',
                    fontSize: 12,
                    fontWeight: 'bold',
                    distanceToLabelLine: 10,
                    // 添加标签阴影
                    textShadowBlur: 5,
                    textShadowColor: 'rgba(0, 0, 0, 0.8)'
                },
                labelLine: {
                    show: true,
                    length: 15,
                    length2: 15,
                    lineStyle: {
                        color: '#8892b0',
                        width: 1,
                        type: 'solid',
                        // 添加虚线动画
                        curveness: 0.3,
                        animation: true,
                        animationDuration: 1500,
                        animationEasing: 'cubicOut'
                    }
                }
            },
            // 中心显示统计信息
            {
                name: '中心统计',
                type: 'pie',
                radius: ['30%', '35%'],
                center: ['65%', '50%'],
                data: [{
                    value: 1,
                    itemStyle: {
                        color: new echarts.graphic.RadialGradient(0.5, 0.5, 1, [
                            { offset: 0, color: 'rgba(10, 14, 39, 0.8)' },
                            { offset: 1, color: 'rgba(10, 14, 39, 0.5)' }
                        ]),
                        borderColor: '#4299e1',
                        borderWidth: 1
                    },
                    label: {
                        show: true,
                        formatter: function() {
                            return `总数\n${totalCount}`;
                        },
                        color: '#fff',
                        fontSize: 16,
                        fontWeight: 'bold'
                    }
                }],
                emphasis: {
                    itemStyle: {
                        shadowBlur: 15,
                        shadowOffsetX: 0,
                        shadowColor: 'rgba(66, 153, 225, 0.5)'
                    }
                }
            },
            // 添加一个内层小圆点增加视觉效果
            {
                name: '内圈装饰',
                type: 'pie',
                radius: ['15%', '20%'],
                center: ['65%', '50%'],
                data: [
                    {
                        value: 1,
                        itemStyle: {
                            color: new echarts.graphic.RadialGradient(0.5, 0.5, 1, [
                                { offset: 0, color: '#4299e1' },
                                { offset: 1, color: '#1e3a8a' }
                            ]),
                            // 添加脉动效果的样式
                            borderColor: '#fff',
                            borderWidth: 1
                        }
                    }
                ],
                label: {
                    show: false
                },
                emphasis: {
                    itemStyle: {
                        shadowBlur: 15,
                        shadowOffsetX: 0,
                        shadowColor: 'rgba(66, 153, 225, 0.8)'
                    }
                },
                // 添加脉动动画
                animationType: 'scale',
                animationEasing: 'easeInOutSine',
                animationDuration: 2000,
                animationDelay: 500,
                animationRepeat: Infinity,
                animationRepeatDelay: 1000
            }
        ]
    });
    
    // 添加点击事件处理
    categoryChart.on('click', function(params) {
        // 避免处理内圈装饰和中心统计的数据
        if (params.seriesName === '内圈装饰' || params.seriesName === '中心统计') return;
        
        // 创建临时元素显示点击反馈
        const chartDom = document.getElementById('hotspotCategoryChart');
        const rect = chartDom.getBoundingClientRect();
        const tooltip = document.createElement('div');
        
        tooltip.innerHTML = `
            <div style="
                padding: 15px;
                background: rgba(10, 14, 39, 0.95);
                border: 2px solid ${params.color};
                border-radius: 10px;
                color: #fff;
                box-shadow: 0 5px 20px rgba(0, 0, 0, 0.5);
                z-index: 9999;
                text-align: center;
            ">
                <div style="font-size: 24px; margin-bottom: 5px;">${getCategoryIcon(params.name)}</div>
                <div style="font-weight: bold; margin-bottom: 5px;">${params.name}</div>
                <div>数量: <span style="color: #4299e1; font-weight: bold;">${params.value}</span></div>
                <div>占比: <span style="color: #4299e1; font-weight: bold;">${params.percent}%</span></div>
            </div>
        `;
        
        tooltip.style.cssText = `
            position: fixed;
            left: ${rect.left + rect.width / 2}px;
            top: ${rect.top + rect.height / 2}px;
            transform: translate(-50%, -50%);
            opacity: 0;
            transition: opacity 0.3s ease, transform 0.6s cubic-bezier(0.175, 0.885, 0.32, 1.275);
            pointer-events: none;
            z-index: 9999;
        `;
        
        document.body.appendChild(tooltip);
        
        // 触发显示动画
        setTimeout(() => {
            tooltip.style.opacity = '1';
            tooltip.style.transform = 'translate(-50%, -50%) scale(1.1)';
        }, 10);
        
        // 自动消失
        setTimeout(() => {
            tooltip.style.opacity = '0';
            tooltip.style.transform = 'translate(-50%, -50%) scale(0.8)';
            setTimeout(() => {
                document.body.removeChild(tooltip);
            }, 300);
        }, 1500);
        
        // 添加图表区域的高亮效果
        const flashElement = document.createElement('div');
        flashElement.style.cssText = `
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: radial-gradient(circle at ${params.event.offsetX}px ${params.event.offsetY}px, ${params.color}40, transparent 70%);
            pointer-events: none;
            opacity: 0;
            z-index: 10;
        `;
        
        chartDom.appendChild(flashElement);
        
        // 触发闪光动画
        setTimeout(() => {
            flashElement.style.transition = 'opacity 0.6s ease';
            flashElement.style.opacity = '0.8';
            
            setTimeout(() => {
                flashElement.style.opacity = '0';
                setTimeout(() => {
                    chartDom.removeChild(flashElement);
                }, 600);
            }, 300);
        }, 10);
    });
    
    // 添加鼠标悬停事件增强交互体验
    categoryChart.on('mouseover', function(params) {
        if (params.seriesName === '热点分类') {
            // 可以在这里添加额外的悬停效果
            // 例如：高亮对应的图例项
        }
    });
}

// 调整颜色亮度的辅助函数
function adjustColorBrightness(color, amount) {
    // 移除#前缀
    color = color.replace(/^#/, '');
    
    // 解析RGB值
    let r = parseInt(color.substring(0, 2), 16);
    let g = parseInt(color.substring(2, 4), 16);
    let b = parseInt(color.substring(4, 6), 16);
    
    // 调整亮度
    r = Math.max(0, Math.min(255, r + amount));
    g = Math.max(0, Math.min(255, g + amount));
    b = Math.max(0, Math.min(255, b + amount));
    
    // 转换回十六进制
    return '#' + 
        Math.round(r).toString(16).padStart(2, '0') +
        Math.round(g).toString(16).padStart(2, '0') +
        Math.round(b).toString(16).padStart(2, '0');
}

/* ========== 热门话题列表 ========== */
// 话题关键词映射表，用于生成相关图片
const topicKeywordsMap = {
    '元旦假期': ['元旦', '假期', '新年', '旅行', '节日'],
    '新年计划': ['新年', '计划', '目标', '2025', '规划'],
    '春节出行': ['春节', '春运', '旅行', '回家', '团圆'],
    '人工智能': ['人工智能', 'AI', '大模型', '科技', '智能'],
    '冬奥会': ['冬奥会', '冰雪运动', '冰上运动', '滑雪', '滑冰'],
    '新能源车': ['新能源', '电动车', '汽车', '环保', '科技'],
    'ChatGPT': ['ChatGPT', 'AI', '聊天机器人', '智能助手', '技术'],
    '元宇宙': ['元宇宙', '虚拟现实', 'VR', '虚拟世界', '数字孪生'],
    '健康饮食': ['健康', '饮食', '营养', '蔬果', '健康生活'],
    '数字人民币': ['数字人民币', '数字货币', '支付', '金融科技', '央行数字货币']
};

// 从标题提取关键词的函数
function extractKeywordsFromTitle(title) {
    // 移除话题标签符号
    const cleanTitle = title.replace(/#/g, '');
    
    // 查找匹配的关键词组
    for (const [key, keywords] of Object.entries(topicKeywordsMap)) {
        if (cleanTitle.includes(key)) {
            return keywords;
        }
    }
    
    // 如果没有匹配的关键词组，返回通用关键词
    return ['热门', '趋势', '新闻', '热点', '话题'];
}

// 为话题生成相关图片URL的函数
// 本地模拟图片服务适配器，支持多种图片来源
const imageServiceAdapters = {
    // 本地模拟抖音风格图片服务
    douyin: {
        // 本地模拟抖音图片搜索API
        getImageUrl: (topic, keywords, width, height) => {
            // 使用本地模拟的图片集合，根据关键词和类别返回相关图片
            const category = determineCategoryFromKeywords(keywords);
            // 预定义的分类图片集合
            const categoryImages = {
                'holiday': ['https://picsum.photos/id/10/800/400', 'https://picsum.photos/id/11/800/400', 'https://picsum.photos/id/12/800/400'],
                'spring_festival': ['https://picsum.photos/id/13/800/400', 'https://picsum.photos/id/14/800/400', 'https://picsum.photos/id/15/800/400'],
                'technology': ['https://picsum.photos/id/20/800/400', 'https://picsum.photos/id/21/800/400', 'https://picsum.photos/id/22/800/400'],
                'sports': ['https://picsum.photos/id/27/800/400', 'https://picsum.photos/id/28/800/400', 'https://picsum.photos/id/29/800/400'],
                'auto': ['https://picsum.photos/id/31/800/400', 'https://picsum.photos/id/32/800/400', 'https://picsum.photos/id/33/800/400'],
                'metaverse': ['https://picsum.photos/id/36/800/400', 'https://picsum.photos/id/37/800/400', 'https://picsum.photos/id/38/800/400'],
                'health': ['https://picsum.photos/id/42/800/400', 'https://picsum.photos/id/43/800/400', 'https://picsum.photos/id/44/800/400'],
                'finance': ['https://picsum.photos/id/48/800/400', 'https://picsum.photos/id/49/800/400', 'https://picsum.photos/id/50/800/400'],
                'general': ['https://picsum.photos/id/60/800/400', 'https://picsum.photos/id/61/800/400', 'https://picsum.photos/id/62/800/400']
            };
            
            // 根据类别获取图片集合，不存在则使用通用图片
            const images = categoryImages[category] || categoryImages.general;
            // 根据话题ID选择一个固定的图片
            const imageIndex = topic.id % images.length;
            // 调整URL以匹配请求的尺寸
            return images[imageIndex].replace('800/400', `${width}/${height}`);
        }
    },
    // 本地模拟相关照片库服务
    relatedPhotos: {
        // 本地模拟相关照片库API
        getImageUrl: (topic, keywords, width, height) => {
            // 根据话题内容和关键词生成相关图片URL
            const category = determineCategoryFromKeywords(keywords);
            // 预定义的分类图片集合
            const categoryImages = {
                'holiday': ['https://picsum.photos/id/1/800/400', 'https://picsum.photos/id/2/800/400', 'https://picsum.photos/id/3/800/400'],
                'spring_festival': ['https://picsum.photos/id/4/800/400', 'https://picsum.photos/id/5/800/400', 'https://picsum.photos/id/6/800/400'],
                'technology': ['https://picsum.photos/id/7/800/400', 'https://picsum.photos/id/8/800/400', 'https://picsum.photos/id/9/800/400'],
                'sports': ['https://picsum.photos/id/16/800/400', 'https://picsum.photos/id/17/800/400', 'https://picsum.photos/id/18/800/400'],
                'auto': ['https://picsum.photos/id/34/800/400', 'https://picsum.photos/id/35/800/400', 'https://picsum.photos/id/39/800/400'],
                'metaverse': ['https://picsum.photos/id/40/800/400', 'https://picsum.photos/id/41/800/400', 'https://picsum.photos/id/45/800/400'],
                'health': ['https://picsum.photos/id/46/800/400', 'https://picsum.photos/id/47/800/400', 'https://picsum.photos/id/51/800/400'],
                'finance': ['https://picsum.photos/id/52/800/400', 'https://picsum.photos/id/53/800/400', 'https://picsum.photos/id/54/800/400'],
                'general': ['https://picsum.photos/id/55/800/400', 'https://picsum.photos/id/56/800/400', 'https://picsum.photos/id/57/800/400']
            };
            
            // 根据类别获取图片集合，不存在则使用通用图片
            const images = categoryImages[category] || categoryImages.general;
            // 根据话题ID选择一个固定的图片
            const imageIndex = (topic.id + 1) % images.length;
            // 调整URL以匹配请求的尺寸
            return images[imageIndex].replace('800/400', `${width}/${height}`);
        }
    },
    // 默认备用服务
    default: {
        getImageUrl: (topic, keywords, width, height) => {
            // 使用picsum作为默认备用，确保使用固定ID以保证一致性
            const seed = topic.id + keywords.join('').length;
            // 使用固定ID的picsum图片，确保图片加载可靠
            const imageId = (seed % 100) + 1; // picsum有很多ID可用
            return `https://picsum.photos/id/${imageId}/${width}/${height}`;
        }
    }
};

// 根据关键词确定图片类别
function determineCategoryFromKeywords(keywords) {
    const categoryMap = {
        '元旦|新年|假期|节日': 'holiday',
        '春节|回家|团圆|春运': 'spring_festival',
        '人工智能|AI|大模型|ChatGPT': 'technology',
        '冬奥会|运动|体育': 'sports',
        '新能源车|汽车|电动车': 'auto',
        '元宇宙|虚拟现实|VR': 'metaverse',
        '健康|饮食|营养': 'health',
        '数字人民币|金融': 'finance'
    };
    
    // 查找匹配的类别
    for (const [pattern, category] of Object.entries(categoryMap)) {
        const regex = new RegExp(pattern);
        if (keywords.some(keyword => regex.test(keyword))) {
            return category;
        }
    }
    return 'general';
}

// 图片缓存机制，避免重复加载相同的图片
const imageCache = new Map();

// 优化的图片加载器，支持故障转移、缓存和更快的响应
function loadImageWithFallback(url, fallbackUrls) {
    // 检查缓存中是否已有此图片
    if (imageCache.has(url)) {
        console.log(`Using cached image: ${url}`);
        return Promise.resolve(url);
    }
    
    return new Promise((resolve, reject) => {
        // 创建图片对象
        const img = new Image();
        
        // 设置加载超时
        const timeoutId = setTimeout(() => {
            if (img.complete === false) {
                console.log(`Image loading timeout: ${url}`);
                tryNextFallback();
            }
        }, 3000); // 减少超时时间以加快故障转移
        
        // 加载成功处理
        img.onload = () => {
            clearTimeout(timeoutId);
            // 将成功加载的图片添加到缓存
            imageCache.set(url, true);
            resolve(url);
        };
        
        // 加载失败处理
        img.onerror = () => {
            clearTimeout(timeoutId);
            tryNextFallback();
        };
        
        // 网络错误处理
        img.onabort = () => {
            clearTimeout(timeoutId);
            console.log(`Image loading aborted: ${url}`);
            tryNextFallback();
        };
        
        // 尝试下一个备用图片
        function tryNextFallback() {
            if (fallbackUrls.length > 0) {
                console.log(`Falling back to next image source: ${fallbackUrls[0]}`);
                loadImageWithFallback(fallbackUrls[0], fallbackUrls.slice(1))
                    .then(resolve)
                    .catch(reject);
            } else {
                reject(new Error('All image sources failed to load'));
            }
        }
        
        // 设置跨域支持，确保兼容性
        img.crossOrigin = 'anonymous';
        
        // 开始加载图片
        img.src = url;
    });
}

// 批量预加载图片的函数
function preloadImages(imageUrls) {
    return Promise.all(
        imageUrls.map(url => {
            return new Promise((resolve, reject) => {
                // 如果已缓存，直接解析
                if (imageCache.has(url)) {
                    resolve(url);
                    return;
                }
                
                const img = new Image();
                img.onload = () => {
                    imageCache.set(url, true);
                    resolve(url);
                };
                img.onerror = reject;
                img.crossOrigin = 'anonymous';
                img.src = url;
            });
        })
    );
}

function generateRelevantImageUrl(topic, width, height) {
    const keywords = extractKeywordsFromTitle(topic.title);
    
    if (!keywords || keywords.length === 0) {
        // 如果没有关键词，使用默认服务
        return imageServiceAdapters.default.getImageUrl(topic, ['default'], width, height);
    }
    
    // 生成所有可用服务的图片URL作为候选
    const candidateUrls = [
        imageServiceAdapters.douyin.getImageUrl(topic, keywords, width, height),
        imageServiceAdapters.relatedPhotos.getImageUrl(topic, keywords, width, height),
        imageServiceAdapters.default.getImageUrl(topic, keywords, width, height)
    ];
    
    // 返回首选URL，实际的故障转移逻辑在loadImageWithFallback中处理
    // 由于我们无法在这个函数中进行异步操作，我们返回首选URL并在使用时进行验证
    return candidateUrls[0];
}

// 预定义话题数据，后续会动态生成图片URL
let hotTopics = [
    { 
        id: 1, 
        title: '#元旦假期安排#', 
        heat: 987523, 
        trend: 'up',
        description: '2025年元旦假期即将到来，大家都在热议如何安排这个小长假。根据最新数据显示，短途旅游、家庭聚会和文化活动成为最受欢迎的选择。许多热门景点已经开始预售门票，建议提前规划行程。'
    },
    { 
        id: 2, 
        title: '#2025年新年计划#', 
        heat: 876432, 
        trend: 'up',
        description: '随着2025年的到来，制定新年计划成为热门话题。健康管理、职业发展和学习新技能是人们最关注的三个方面。专家建议，设定具体、可衡量的目标更容易实现。'
    },
    { 
        id: 3, 
        title: '#春节出行攻略#', 
        heat: 765432, 
        trend: 'up',
        description: '2025年春节临近，出行攻略成为热门搜索。今年春运预计将有超过20亿人次的流动，提前购票和错峰出行是关键。同时，多地推出了春节特色活动，为旅客提供了更多选择。'
    },
    { 
        id: 4, 
        title: '#人工智能大模型#', 
        heat: 654321, 
        trend: 'up',
        description: '人工智能大模型技术持续突破，最新的多模态模型展现出惊人的能力。从内容创作到科学研究，AI正在各行各业发挥越来越重要的作用。专家预测，2025年将是AI应用落地的关键一年。'
    },
    { 
        id: 5, 
        title: '#冬奥会最新消息#', 
        heat: 543210, 
        trend: 'up',
        description: '冬奥会筹备工作正在紧锣密鼓地进行中。各国选手已经开始最后的备战，多个比赛场馆已完成验收。票务信息和赛事日程将在近期公布，体育迷们可以开始规划观赛安排。'
    },
    { 
        id: 6, 
        title: '#新能源车销量创新高#', 
        heat: 432109, 
        trend: 'up',
        description: '最新数据显示，12月份新能源车销量同比增长超过80%，创历史新高。随着充电基础设施的完善和续航能力的提升，越来越多的消费者选择新能源车。多家车企也宣布了新的电动车型计划。'
    },
    { 
        id: 7, 
        title: '#ChatGPT新功能#', 
        heat: 321098, 
        trend: 'up',
        description: 'ChatGPT推出了多项新功能，包括实时信息获取、多语言翻译增强和自定义训练能力。这些更新大大提升了AI助手的实用性，引发了广泛讨论。用户可以通过API或网页版体验这些新功能。'
    },
    { 
        id: 8, 
        title: '#元宇宙发展现状#', 
        heat: 210987, 
        trend: 'down',
        description: '元宇宙概念经历了从狂热到理性的转变，目前进入了稳步发展阶段。多家科技巨头调整了元宇宙战略，更加注重实用场景的开发。虚拟办公、在线教育和数字娱乐成为元宇宙应用的主要方向。'
    },
    { 
        id: 9, 
        title: '#健康饮食指南#', 
        heat: 198765, 
        trend: 'up',
        description: '随着健康意识的提高，科学饮食成为热门话题。营养专家建议，均衡摄入各类营养素，减少加工食品的消费，多吃新鲜蔬果。此外，饮食习惯与心理健康的关联也受到越来越多的关注。'
    },
    { 
        id: 10, 
        title: '#数字人民币试点#', 
        heat: 187654, 
        trend: 'up',
        description: '数字人民币试点范围继续扩大，目前已覆盖全国多个省市。用户反馈显示，数字人民币在支付便捷性、交易安全性和跨境支付方面具有显著优势。随着更多商家的接入，数字人民币的使用场景将更加丰富。'
    }
];

// 为所有话题生成相关图片URL
function initializeTopicImages() {
    // 收集所有需要预加载的图片URL
    const allImagesToPreload = [];
    
    // 为每个话题生成图片URL
    hotTopics.forEach(topic => {
        const keywords = extractKeywordsFromTitle(topic.title);
        
        // 生成所有候选URL
        const smallImageCandidates = [
            imageServiceAdapters.douyin.getImageUrl(topic, keywords, 200, 200),
            imageServiceAdapters.relatedPhotos.getImageUrl(topic, keywords, 200, 200),
            imageServiceAdapters.default.getImageUrl(topic, keywords, 200, 200)
        ];
        
        const detailImageCandidates = [
            imageServiceAdapters.douyin.getImageUrl(topic, keywords, 800, 400),
            imageServiceAdapters.relatedPhotos.getImageUrl(topic, keywords, 800, 400),
            imageServiceAdapters.default.getImageUrl(topic, keywords, 800, 400)
        ];
        
        // 存储候选URL
        topic.smallImageCandidates = smallImageCandidates;
        topic.detailImageCandidates = detailImageCandidates;
        
        // 设置初始默认图片（从候选列表中选择最可靠的）
        topic.smallImage = smallImageCandidates[2]; // 默认使用picsum作为初始图片
        topic.detailImage = detailImageCandidates[2];
        
        // 收集所有图片URL用于预加载（优先预加载默认图片）
        allImagesToPreload.push(smallImageCandidates[2], detailImageCandidates[2]);
    });
    
    // 先预加载所有默认图片，确保至少有图片可用
    preloadImages(allImagesToPreload.slice(0, hotTopics.length * 2)) // 只预加载默认图片
        .then(() => {
            console.log('Default images preloaded successfully');
            
            // 然后为每个话题尝试加载首选图片
            hotTopics.forEach(topic => {
                // 尝试加载小图片的首选来源
                loadImageWithFallback(topic.smallImageCandidates[0], topic.smallImageCandidates.slice(1))
                    .then(validUrl => {
                        topic.smallImage = validUrl;
                        // 更新已渲染的DOM元素
                        const topicEl = document.querySelector(`[data-topic-id="${topic.id}"]`);
                        if (topicEl) {
                            const imgEl = topicEl.querySelector('.topic-image');
                            if (imgEl) {
                                imgEl.src = validUrl;
                                // 添加淡入效果
                                imgEl.style.opacity = '0';
                                imgEl.style.transition = 'opacity 0.3s ease-in';
                                setTimeout(() => {
                                    imgEl.style.opacity = '1';
                                }, 50);
                            }
                        }
                    })
                    .catch(err => {
                        console.warn(`Failed to load small image for topic ${topic.title}:`, err);
                        // 即使失败，我们仍然有初始默认图片可用
                    });
                
                // 尝试加载详情图片的首选来源
                loadImageWithFallback(topic.detailImageCandidates[0], topic.detailImageCandidates.slice(1))
                    .then(validUrl => {
                        topic.detailImage = validUrl;
                    })
                    .catch(err => {
                        console.warn(`Failed to load detail image for topic ${topic.title}:`, err);
                    });
            });
        })
        .catch(err => {
            console.error('Error during image preloading:', err);
            // 即使预加载失败，仍然尝试单独加载每个图片
            hotTopics.forEach(topic => {
                // 使用现有的初始默认图片
            });
        });
}

// 渲染热门话题列表
function renderHotTopicsList() {
    const container = document.querySelector('#hotTopicsList');
    if (!container) return;
    container.innerHTML = '';
    
    hotTopics.forEach((topic, index) => {
        const topicElement = document.createElement('div');
        topicElement.className = 'hot-topic-item';
        topicElement.dataset.trend = topic.trend;
        topicElement.dataset.id = topic.id;
        
        const trendIcon = topic.trend === 'up' ? '📈' : '📉';
        const trendClass = topic.trend === 'up' ? 'trend-up' : 'trend-down';
        
        // 为所有话题添加小图片（不仅限于前三名）
        const smallImageHtml = topic.smallImage ? 
            `<img src="${topic.smallImage}" alt="${topic.title}" class="topic-image-small" loading="lazy">` : '';
        
        // 提取并显示相关关键词
        const keywords = extractKeywordsFromTitle(topic.title).slice(0, 3);
        const keywordsHtml = keywords.map(keyword => 
            `<span class="topic-keyword">${keyword}</span>`
        ).join(' ');
        
        topicElement.innerHTML = `
            <div class="topic-rank">${index + 1}</div>
            ${smallImageHtml}
            <div class="topic-content">
                <div class="topic-title">${topic.title}</div>
                <div class="topic-keywords">${keywordsHtml}</div>
                <div class="topic-stats">
                    <span class="topic-heat">🔥 ${(topic.heat / 10000).toFixed(1)}万</span>
                    <span class="topic-trend ${trendClass}">${trendIcon}</span>
                </div>
            </div>
        `;
        
        // 添加点击事件
        topicElement.addEventListener('click', function() {
            // 移除其他项的选中状态
            document.querySelectorAll('.hot-topic-item').forEach(item => {
                item.classList.remove('active');
            });
            // 添加当前项的选中状态
            this.classList.add('active');
            // 显示话题详情
            showTopicDetail(topic);
        });
        
        // 添加鼠标悬停效果
        topicElement.addEventListener('mouseenter', function() {
            this.style.transform = 'translateX(5px)';
            this.style.boxShadow = '0 4px 12px rgba(0, 0, 0, 0.15)';
        });
        
        topicElement.addEventListener('mouseleave', function() {
            this.style.transform = 'translateX(0)';
            this.style.boxShadow = 'none';
        });
        
        // 添加动画效果
        topicElement.style.opacity = '0';
        topicElement.style.transform = 'translateX(-20px)';
        topicElement.style.transition = 'all 0.3s ease';
        
        setTimeout(() => {
            topicElement.style.opacity = '1';
            topicElement.style.transform = 'translateX(0)';
        }, 100 + index * 100);
        
        container.appendChild(topicElement);
    });
}

// 显示话题详情
function showTopicDetail(topic) {
    const detailContainer = document.querySelector('#topicDetailContent');
    if (!detailContainer || !topic) return;
    
    // 提取关键词用于展示
    const keywords = extractKeywordsFromTitle(topic.title);
    const keywordsHtml = keywords.map(keyword => 
        `<span class="detail-keyword">#${keyword}#</span>`
    ).join(' ');
    
    // 创建详情内容，添加图片加载优化和错误处理
    const detailHtml = `
        <div class="detail-content">
            <div class="detail-image-container">
                <img src="${topic.detailImage}" alt="${topic.title}" class="detail-image" 
                     loading="lazy" 
                     onerror="this.src='https://picsum.photos/800/400?fallback=true'; this.onerror=null;">
                <div class="detail-image-overlay">
                    <div class="image-source-info">图片来源：抖音开放平台</div>
                </div>
            </div>
            <h3 class="detail-title">${topic.title}</h3>
            <div class="detail-meta">
                <span class="detail-heat">🔥 热度: ${(topic.heat / 10000).toFixed(1)}万</span>
                <span class="detail-trend">${topic.trend === 'up' ? '📈 上升' : '📉 下降'}</span>
            </div>
            <div class="detail-keywords-container">
                ${keywordsHtml}
            </div>
            <p class="detail-description">${topic.description}</p>
        </div>
    `;
    
    // 添加淡入动画和内容过渡效果
    detailContainer.style.opacity = '0';
    detailContainer.style.transform = 'translateY(10px)';
    setTimeout(() => {
        detailContainer.innerHTML = detailHtml;
        // 添加图片加载动画
        const img = detailContainer.querySelector('.detail-image');
        if (img) {
            img.style.opacity = '0';
            img.style.transition = 'opacity 0.5s ease';
            img.onload = () => {
                img.style.opacity = '1';
            };
        }
        
        detailContainer.style.opacity = '1';
        detailContainer.style.transform = 'translateY(0)';
        detailContainer.style.transition = 'all 0.5s ease';
    }, 200);
}

/* 更新热点趋势数据 */
function updateTrendData() {
    // 随机更新趋势数据
    for (let i = 0; i < trendData1.length; i++) {
        trendData1[i] = Math.max(50, Math.min(250, trendData1[i] + random(-10, 15)));
        trendData2[i] = Math.max(50, Math.min(150, trendData2[i] + random(-8, 12)));
        trendData3[i] = Math.max(20, Math.min(100, trendData3[i] + random(-5, 8)));
    }
    
    if (hotspotTrendChart) {
        hotspotTrendChart.setOption({
            series: [
                { data: trendData1 },
                { data: trendData2 },
                { data: trendData3 }
            ]
        });
    }
    
    // 随机更新热门话题热度
    hotTopics.forEach(topic => {
        const change = random(-2000, 5000);
        topic.heat = Math.max(100000, topic.heat + change);
        topic.trend = change > 0 ? 'up' : 'down';
        
        // 如果热度变化较大，更新图片以反映新的话题重要性
        if (Math.abs(change) > 3000) {
            topic.smallImage = generateRelevantImageUrl(topic, 200, 200);
            topic.detailImage = generateRelevantImageUrl(topic, 800, 400);
        }
    });
    
    // 重新排序
    hotTopics.sort((a, b) => b.heat - a.heat);
    
    // 高频更新话题列表
    if (Math.random() > 0.8) {
        renderHotTopicsList();
    }
}

/* 更新词云动画效果 */
function updateWordCloudAnimation() {
    const words = document.querySelectorAll('.word-cloud-item');
    words.forEach(word => {
        if (Math.random() > 0.7) {
            const randomRotate = (Math.random() - 0.5) * 20;
            const randomScale = 0.9 + Math.random() * 0.2;
            word.style.transform = `rotate(${randomRotate}deg) scale(${randomScale})`;
        }
    });
}

/* 创建地图容器和功能 */
function initMapFeature() {
    // 检查是否已存在地图容器
    let mapContainer = document.querySelector('#map-container');
    if (!mapContainer) {
        // 在合适位置创建地图容器
        const categoryCard = document.querySelector('#hotspotCategoryChart');
        if (!categoryCard) return;
        const cardElement = categoryCard.closest('.card');
        if (!cardElement) return;
        
        // 创建新的卡片用于地图
        const mapCard = document.createElement('div');
        mapCard.className = 'card';
        mapCard.innerHTML = `
            <div class="card-header">
                <h3>热点地区分布</h3>
                <div class="card-controls">
                    <button id="mapToggleBtn" class="btn btn-small">切换地图</button>
                </div>
            </div>
            <div class="card-body">
                <div id="map-container" style="width: 100%; height: 400px;"></div>
            </div>
        `;
        
        // 插入到分类卡片后
        cardElement.parentNode.insertBefore(mapCard, cardElement.nextSibling);
        mapContainer = document.querySelector('#map-container');
        if (!mapContainer) return;
    }
    
    let mapChart = null;
    if (mapContainer) {
        // 初始化地图
        mapChart = echarts.init(mapContainer);
        let currentMap = 'world'; // 当前显示的地图类型
        
        // 中国各省份热点数据
        const chinaProvinceData = [
            { name: '北京', value: 95 },
            { name: '上海', value: 92 },
            { name: '广东', value: 88 },
            { name: '浙江', value: 85 },
            { name: '江苏', value: 83 },
            { name: '四川', value: 78 },
            { name: '湖北', value: 75 },
            { name: '河南', value: 72 },
            { name: '山东', value: 70 },
            { name: '福建', value: 68 },
            { name: '湖南', value: 65 },
            { name: '安徽', value: 62 },
            { name: '河北', value: 60 },
            { name: '陕西', value: 58 },
            { name: '重庆', value: 55 }
        ];
        
        // 世界地图配置
        function getWorldMapOption() {
            return {
                backgroundColor: 'transparent',
                tooltip: {
                    trigger: 'item',
                    formatter: '{b}: {c}'
                },
                visualMap: {
                    min: 0,
                    max: 100,
                    left: 'left',
                    top: 'bottom',
                    text: ['高', '低'],
                    textStyle: {
                        color: '#8892b0'
                    },
                    inRange: {
                        color: ['#e5e9f2', '#4d79ff', '#3359e7', '#1f3da8']
                    }
                },
                series: [
                    {
                        name: '热点数据',
                        type: 'map',
                        map: 'world',
                        roam: true,
                        data: [
                            { name: 'China', value: 85 },
                            { name: 'United States', value: 76 },
                            { name: 'Russia', value: 45 },
                            { name: 'Japan', value: 68 },
                            { name: 'Korea', value: 52 },
                            { name: 'United Kingdom', value: 32 },
                            { name: 'France', value: 38 },
                            { name: 'Germany', value: 41 },
                            { name: 'Canada', value: 29 },
                            { name: 'Australia', value: 27 }
                        ],
                        emphasis: {
                            itemStyle: {
                                areaColor: '#ffc658'
                            },
                            label: {
                                show: true,
                                fontSize: 14
                            }
                        }
                    }
                ]
            };
        }
        
        // 中国地图配置
        function getChinaMapOption() {
            return {
                backgroundColor: 'transparent',
                tooltip: {
                    trigger: 'item',
                    formatter: '{b}: {c}'
                },
                visualMap: {
                    min: 0,
                    max: 100,
                    left: 'left',
                    top: 'bottom',
                    text: ['高', '低'],
                    textStyle: {
                        color: '#8892b0'
                    },
                    inRange: {
                        color: ['#e5e9f2', '#4d79ff', '#3359e7', '#1f3da8']
                    }
                },
                series: [
                    {
                        name: '热点数据',
                        type: 'map',
                        map: 'china',
                        roam: true,
                        data: chinaProvinceData,
                        emphasis: {
                            itemStyle: {
                                areaColor: '#ffc658'
                            },
                            label: {
                                show: true,
                                fontSize: 12
                            }
                        }
                    }
                ]
            };
        }
        
        // 初始化地图
        mapChart.setOption(getWorldMapOption());
        
        // 加载中国地图数据
        if (!echarts.getMap('china')) {
            const chinaMapUrl = 'https://cdn.jsdelivr.net/npm/echarts/map/json/china.json';
            fetch(chinaMapUrl)
                .then(response => response.json())
                .then(mapData => {
                    echarts.registerMap('china', mapData);
                })
                .catch(error => {
                    console.error('加载中国地图数据失败:', error);
                });
        }
        
        // 地图点击事件，切换到中国地图
        mapChart.on('click', function(params) {
            if (params.name === 'China' && currentMap === 'world') {
                currentMap = 'china';
                mapChart.setOption(getChinaMapOption());
            }
        });
        
        // 按钮切换地图
        const toggleBtn = document.querySelector('#mapToggleBtn');
        if (toggleBtn) {
            toggleBtn.addEventListener('click', function() {
                currentMap = currentMap === 'world' ? 'china' : 'world';
                mapChart.setOption(currentMap === 'world' ? getWorldMapOption() : getChinaMapOption());
            });
        }
        
        // 地图数据更新函数
        window.updateMapData = function() {
            if (!mapChart) return;
            let option = mapChart.getOption();
            if (option && option.series && option.series[0]) {
                let series = option.series[0];
                
                // 随机更新部分数据点
                if (series.data) {
                    series.data.forEach(item => {
                        if (Math.random() > 0.7) {
                            item.value += random(-3, 5);
                            item.value = Math.max(0, Math.min(100, item.value));
                        }
                    });
                    
                    if (mapChart) {
                        mapChart.setOption({
                            series: [series]
                        });
                    }
                }
            }
        };
        
        // 响应式重绘
        window.addEventListener('resize', () => {
            if (mapChart) {
                mapChart.resize();
            }
        });
    }
}

/* 页面进入动画 */
function pageEnterAnimation() {
    const elements = document.querySelectorAll('.card');
    elements.forEach((el, index) => {
        el.style.opacity = '0';
        el.style.transform = 'translateY(20px)';
        el.style.transition = 'all 0.5s ease';
        
        setTimeout(() => {
            el.style.opacity = '1';
            el.style.transform = 'translateY(0)';
        }, 100 + index * 150);
    });
}

/* 初始化页面 */
function initPage() {
    // 初始化话题图片
    initializeTopicImages();
    
    // 渲染初始词云
    refreshHotspot();
    
    // 初始化图表
    initHotspotTrendChart();
    initCategoryChart();
    
    // 创建地图功能
    initMapFeature();
    
    // 渲染热门话题列表
    renderHotTopicsList();
    
    // 启动每秒更新数据
    setInterval(function() {
        updateTrendData();
        // 更新词云动画
        updateWordCloudAnimation();
        // 更新地图数据
        if (window.updateMapData) {
            window.updateMapData();
        }
        // 随机刷新词云内容
        if (Math.random() > 0.95) {
            refreshHotspot();
        }
    }, 1000);
    
    // 页面进入动画
    pageEnterAnimation();
    
    // 监听窗口大小变化，重新调整布局
    window.addEventListener('resize', function() {
        // 延迟执行以避免频繁更新
        if (this.resizeTimer) clearTimeout(this.resizeTimer);
        this.resizeTimer = setTimeout(function() {
            // 重新渲染话题列表，可能需要调整图片大小
            renderHotTopicsList();
        }, 300);
    });
}

// 页面加载完成后初始化
window.addEventListener('load', initPage);

/* 响应式重绘 */
window.addEventListener('resize', () => {
    hotspotTrendChart && hotspotTrendChart.resize();
    categoryChart && categoryChart.resize();
});